package com.lk.api;

import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ApiDemos extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        String path = intent.getStringExtra("com.lk.api.Path");
//        Log.d("onCreate_path:", "" + path);

        if (path == null) {
            path = "";
        }

        setListAdapter(new SimpleAdapter(this, getData(path), android.R.layout.simple_list_item_1, new String[]{"title"}, new int[]{android.R.id.text1}));
//        getListAdapter();
        getListView().setTextFilterEnabled(true);
    }


    /**
     * 准备数据
     *
     * @param prefix
     * @return
     */
    protected List<Map<String, Object>> getData(String prefix) {
        List<Map<String, Object>> myData = new ArrayList<Map<String, Object>>();
//
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_SAMPLE_CODE);

        PackageManager pm = getPackageManager();
        List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);

        if (null == list) {
            return myData;
        }
        // 前缀路径
        String[] prefixPath;
        // 前缀与斜线
        String prefixWithSlash = prefix;

        if (prefix.equals("")) {
            prefixPath = null;
        } else {
            prefixPath = prefix.split("/");
            prefixWithSlash = prefix + "/";
//            Log.d("prefixPath:", "" + prefixPath);
//            Log.d("prefixWithSlash:", "" + prefixWithSlash);
        }

        int len = list.size();
        Map<String, Boolean> entries = new HashMap<String, Boolean>();

        for (int i = 0; i < len; i++) {
            ResolveInfo info = list.get(i);
            CharSequence labelSeq = info.loadLabel(pm);
            // android:label="@string/activity_hello_world"
            String label = labelSeq != null ? labelSeq.toString() : info.activityInfo.name;
//            Log.d("label:", "" + label);

            if (prefixWithSlash.length() == 0 || label.startsWith(prefixWithSlash)) {
                String[] labelPath = label.split("/");
//                Log.d("labelPath:", "" + labelPath);

                String nextLabel = prefixPath == null ? labelPath[0] : labelPath[prefixPath.length];
                if (prefixPath == null) {
                    String l = labelPath[0];
//                    Log.d("l:", l);
                } else {
                    String ll = labelPath[prefixPath.length];
//                    Log.d("ll:", ll);
                }


                if ((prefixPath != null ? prefixPath.length : 0) == labelPath.length - 1) {
                    addItem(myData, nextLabel, activityIntent(info.activityInfo.applicationInfo.packageName, info.activityInfo.name));
//                    Log.d("info.activityInfo.applicationInfo.packageName:", "" + info.activityInfo.applicationInfo.packageName);
//                    Log.d("info.activityInfo.name:", "" + info.activityInfo.name);
                } else {
                    if (entries.get(nextLabel) == null) {
                        addItem(myData, nextLabel, browseIntent(prefix.equals("") ? nextLabel : prefix + "/" + nextLabel));
                        String a = prefix.equals("") ? nextLabel : prefix + "/" + nextLabel;
                        if (a == null) {
//                            Log.d("nextLabel:", "" + nextLabel);
                        } else {
//                            Log.d("prefix + nextLabel:", "" + prefix + "/" + nextLabel);
                        }
                        entries.put(nextLabel, true);
                    }
                }

            }
        }
        Collections.sort(myData, sDisplayNameComparator);

        return myData;

    }

    private final static Comparator<Map<String, Object>> sDisplayNameComparator = new Comparator<Map<String, Object>>() {
        private final Collator collator = Collator.getInstance();

        @Override
        public int compare(Map<String, Object> lhs, Map<String, Object> rhs) {
            return collator.compare(lhs.get("title"), rhs.get("title"));
        }
    };

    protected Intent activityIntent(String pkg, String componentName) {
        Intent result = new Intent();
        result.setClassName(pkg, componentName);
        return result;
    }


    protected Intent browseIntent(String path) {
        Intent result = new Intent();
        result.setClass(this, ApiDemos.class);
        result.putExtra("com.lk.api.Path", path);
        return result;

    }

    protected void addItem(List<Map<String, Object>> data, String name, Intent intent) {
        Map<String, Object> temp = new HashMap<String, Object>();
        temp.put("title", name);
        temp.put("intent", intent);
        data.add(temp);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        Map<String, Object> map = (Map<String, Object>) l.getItemAtPosition(position);
//        Log.d("map:", "" + map);
        Intent intent = (Intent) map.get("intent");
//        Log.d("intent:", "" + intent);
//        Toast.makeText(this, "" + ((TextView) v).getText(), Toast.LENGTH_LONG).show();
        startActivity(intent);
    }


//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_api, menu);
//        return true;
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        // Handle action bar item clicks here. The action bar will
//        // automatically handle clicks on the Home/Up button, so long
//        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//
//        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//
//            return true;
//        }
//
//        return super.onOptionsItemSelected(item);
//    }
}
